package com.gaoyi.websocket.utils;

import com.gaoyi.websocket.mapper.MessageMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class RedisToMysql extends QuartzJobBean {

    private boolean flag = true;

    @Resource
    MessageMapper messageMapper;
    @Resource
    RedisUtils redisUtils;

    public boolean insertMysql(){

        Set<String> keys = redisUtils.scanKeys("*MESSAGE_*");
        int k = 0;
        for(String key : keys){
            /**弹出所有值*/
            List<Object> messages = redisUtils.lRange(key,0,-1);
            Long j = redisUtils.length(key);

            /**存入 mysql*/
            int i = messageMapper.insertList(messages);
            if (i > 0){
                //删除key，如果是多线程操作要用到事务
                redisUtils.remove(key);
            }
            if (i != j){
                this.flag = false;
                log.info("插入mysql出错！");
                return false;
            }
            k += j;
        }
            log.info("本次共插入 " + k + " 条数据");
            return flag;
    }

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("###################开始执行定时任务####################");
        insertMysql();
        log.info("###################执行定时任务完成####################");

    }
}
